<?php

namespace Mvc\Core;

use Mvc\Application;
use Mvc\Core\Vendor\Db\DbProxy;
use Mvc\Core\Vendor\Db\Mysqli;

/**
 * Created by PhpStorm.
 * User: 554665488
 * Date: 2018-6-21
 * Time: 18:40
 * @description:使用工厂模式
 * @Author: yfl
 * @QQ 554665488
 */
class Factory
{
    protected static $proxy; //保存代理

    /**
     * @description:获取数据库链接
     * @time:2018-6-22 6:22
     * @Author: yfl
     * @Remark:
     * @param string $name
     * @return bool|mixed|DbProxy|Mysqli
     * @throws \Exception
     */
    public static function getDatabase($name = 'proxy')
    {
        //使用代理
        if ($name == 'proxy') {
            //方式1
            $dbProxy = Register::getInstance('proxy');
            if (!$dbProxy) {
                $dbProxy = new DbProxy();
                Register::setInstance('proxy', $dbProxy);
            }
            return $dbProxy;
            //方式2
//            if (!isset(self::$proxy)) {
//                self::$proxy = new DbProxy();
//            }
//            return self::$proxy;
        }
        //动态加载配置信息获取主从数据库
        $key = 'database_' . $name;
        if ($name == 'slave') {
            $salves = Application::instance(BASE_DIR)->config['database'][$name];
            $db_config = $salves[array_rand($salves)];
        } else {
            $db_config = Application::instance(BASE_DIR)->config['database'][$name];
        }

        $dbObj = Register::getInstance($key);
        if (!$dbObj) {
            $dbObj = new Mysqli();
            $dbObj->connect($db_config['host'], $db_config['user'], $db_config['password'], $db_config['dbname']);
            Register::setInstance($key, $dbObj);
        }
        return $dbObj;
    }

    /**
     * @description:获得模型对象
     * @time:2018-6-22 6:44
     * @Author: yfl
     * @Remark:工厂模式结合注册器模式
     * @param $class
     * @return bool|mixed
     * @throws \Exception
     */
    public static function getModel($class)
    {
        $key = 'model_' . $class;
        $modelObj = Register::getInstance($key);
        if (!$modelObj) {
            $class = "\\Mvc\\App\\Model\\".ucwords($class);
            $modelObj = new $class();
            Register::setInstance($key, $modelObj);
        }
        return $modelObj;
    }
}

